package queue

import (
	"errors"
)

//链表实现的队列
type linkedNode struct {
	node interface{}
	next *linkedNode
}

type NodeQueue struct {
	head, tail *linkedNode
	count      int
}

func NewNodeQueue() *NodeQueue {
	return &NodeQueue{}
}

func (q *NodeQueue) Peek() (interface{}, error) {
	if q.count == 0 {
		return nil, errors.New("queue is empty")
	}
	return q.head.node, nil
}

func (q *NodeQueue) Length() int {
	return q.count
}

func (q *NodeQueue) Pop() (interface{}, error) {
	if q.count == 0 {
		return nil, errors.New("queue is empty")
	}
	result := q.head
	q.head = q.head.next
	q.count--
	return result.node, nil
}

func (q *NodeQueue) Append(node interface{}) {
	if q.count == 0 {
		q.head = &linkedNode{
			node: node,
		}
		q.tail = q.head
	} else {
		q.tail.next = &linkedNode{
			node: node,
		}
		q.tail = q.tail.next
	}
	q.count++
}
